%function [out, st, yin] = upwm_v1(in, Res, edgeType, bThreeLevel, bInterp)
function [out] = upwm_v1(in, Res, edgeType, bThreeLevel, bInterp)

%% Edge type definitions
ET_TAIL_EDGE    = 0;
ET_LEAD_EDGE    = 1;
ET_DOUBLE_EDGE  = 2;

%% oversampling
OSR         = 2^Res;                        % PWM oversampling rate
Nbits_in    = length(in);                   % input signal length (bits)
Nbits_pwm   = Nbits_in * OSR;               % output pwm length (bits)
in_osr      = zeros(1, Nbits_pwm);          % oversampled input
pwm         = zeros(1, Nbits_pwm);          % PWM signal
out         = zeros(1, Nbits_pwm);          % PWM signal

%% interpolation
for i=1:Nbits_in-1
    if(bInterp)
        in_osr((i-1)*OSR+1:i*OSR) = linspace(in(i), in(i+1)-(in(i+1)-in(i))/OSR, OSR);
    else
        in_osr((i-1)*OSR+1:i*OSR) = in(i);
    end
end
in_osr((Nbits_in-1)*OSR+1:Nbits_in*OSR) = linspace(in(Nbits_in), in(1)-(in(1)-in(Nbits_in))/OSR, OSR);

%st          = zeros(1, Nbits_pwm);
%yin          = zeros(1, Nbits_pwm);

%% generate saw_tooth mask
switch(edgeType)
    case ET_TAIL_EDGE
        saw_tooth   = linspace(-1,1,OSR);
    case ET_LEAD_EDGE
        saw_tooth   = linspace(1,-1,OSR);
    case ET_DOUBLE_EDGE
        saw_tooth   = linspace(1, -1, OSR/2+1);
        saw_tooth   = [saw_tooth(1:OSR/2+1) linspace(-1+2/OSR, 1-2/OSR, OSR/2-1)];
%        saw_tooth   = [saw_tooth(1:OSR/2+1) linspace(-1+4/OSR, 1-4/OSR, OSR/2-1)];
        %saw_tooth_2   = linspace(1, -1, OSR/2-1);
        %saw_tooth_2 = [saw_tooth(1:OSR/2) linspace(-1, 1, OSR/2)];
end

%% generate PWM
for i=1:Nbits_in
    for j=1:OSR
        if(bThreeLevel)                 % 3-level pwm
            pwm((i-1)*OSR+j) = (in_osr((i-1)*OSR+j) > saw_tooth(j)) - (-in_osr((i-1)*OSR+j) > saw_tooth(j));
        else
            pwm((i-1)*OSR+j) = in_osr((i-1)*OSR+j) > saw_tooth(j);
            %if(~mod(i,2))
            %    pwm((i-1)*OSR+j) = in_osr((i-1)*OSR+j) > saw_tooth(j);
            %else
            %    pwm((i-1)*OSR+j) = in_osr((i-1)*OSR+j) > saw_tooth_2(j);
            %end
        end
    end
  %  st((i-1)*OSR+1:i*OSR) = saw_tooth;
  %  yin((i-1)*OSR+1:i*OSR) = in_osr((i-1)*OSR+1:i*OSR);
end

%% 3-level treatment


%% output
out = pwm;
    




